package com.sumainfor.pc.gmio.service.impl;

import com.qiniu.util.Json;
import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.PageUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.*;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.gmio.service.HoEleMeterService;
import com.sumainfor.pc.gmio.service.HoWaterMeterService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 */
@Service
public class HoWaterMeterSerivceImpl implements HoWaterMeterService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(HoWaterMeterSerivceImpl.class);
    @Autowired
    private HoWaterMeterMapper hoWaterMeterMapper;
    @Autowired
    private DiChargesDeptMapper diChargesDeptMapper;
    @Autowired
    private SeTenantBillMapper seTenantBillMapper;
    @Autowired
    private ZpcMktFeign zpcMktFeign;
    @Autowired
    private ZzuulFeign zzuulFeign;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private SeBillPayMapper seBillPayMapper;
    @Autowired
    private HoTenantBillMapper hoTenantBillMapper;

    public JsonResult getHoWaterMeterList(Map<String, Object> params) {
        //查询运营部上个月录入的水表信息列表
        List<Map<String,Object>> gmioList=hoWaterMeterMapper.getHoWaterMeterList(params);
        List<String> houidList=new ArrayList<String>();//房源编号列表
        for (Map<String,Object> map1: gmioList){
            if (map1.get("HouId")!=null){
                houidList.add(map1.get("HouId").toString());
            }
        }
        if (houidList.size()==0){
            PageUtils pageUtils = new PageUtils();
            if (params.get("EnterMeter").toString().equals("0")) {
                return pageUtils.getJsonResult(new ArrayList<>(), params, 0);
            }
        }
        System.out.println("运营部查询到的值"+gmioList);
        params.put("houidList",houidList);
        //查询市场部已签约的房源信息
        params.put("WaterType","1");//只查询水表为定价的
        JsonResult marketResult=zpcMktFeign.getHoList(params);
        //保存所有与收费标准关联的编号
        HashSet<Object> conList=new HashSet<Object>();
        //保存公司编号
        HashSet<Object> corList=new HashSet<Object>();
        if (marketResult.get("errorCode").equals("0")) {
            Map<String,Object> marketMap=(Map<String,Object>)marketResult.get("result");
            List<Map<String,Object>> marketList=(List<Map<String,Object>>)marketMap.get("dataList");
            for (Map<String,Object> mktmap : marketList) {
                if (mktmap.get("HouId")!=null){
                    conList.add(mktmap.get("HouId"));
                }
                if (mktmap.get("ComId")!=null){
                    conList.add(mktmap.get("ComId"));
                }
                if (mktmap.get("CorId")!=null){
                    conList.add(mktmap.get("CorId"));
                    corList.add(mktmap.get("CorId"));//保存公司编号传递到网关查询所在市
                }
                if (mktmap.get("MiId")!=null){
                    conList.add(mktmap.get("MiId"));
                }
                if (gmioList!=null){
                    for (Map<String,Object> giomap : gmioList){
                        if (giomap.get("HouId")!=null){
                            if (MapUtils.getString(giomap, "HouId").equals(MapUtils.getString(mktmap, "HouId"))) {
                                mktmap.putAll(giomap);
                            }
                        }
                    }
                }

            }
            if(corList.size()>0) {
                params.put("corList", corList);
                JsonResult zuulResult = zzuulFeign.getSysAreaList(params);
                System.out.println("网关查询到的值:" + zzuulFeign);
                List<Map<String, Object>> zuulList = (List<Map<String, Object>>) zuulResult.get("result");
                for (Map<String, Object> zuulmap : zuulList) {
                    conList.add(zuulmap.get("area_id"));
                }
                /*把房源关联收费标准的编号组装*/
                params.put("conList", conList);
                System.out.println("几何参数:" + conList);
                List<Map<String, Object>> list = diChargesDeptMapper.getChargesDeptList(params);
                System.out.println("收费标准集合:" + list);
                for (Map<String, Object> giomap : list) {
                    for (Map<String, Object> mktmap : marketList) {
                        if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "HouId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "ComId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "MiId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "area_id"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "CorId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        }
                    }
                }
            }
        }
        return marketResult;
    }
    /**
     * 新增水表录入记录
     *
     * @param params
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public JsonResult addHoWaterMeter(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                Map<String,Object> HoMap=new HashMap<String,Object>();
                //水表批次编号
                String UUID3="";
                //水电抄表编号
                String UUID="";
                int number=0;
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "WameId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_water_meter");
                }});
                //账单支出编号
                String UUID2="";
                int number2=0;
                Map<String,Object>uuid2=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "BiId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_tenant_bill");
                }});
                if(uuid!=null &&(!uuid.get("uuid").toString().equals(""))){
                    number=Integer.valueOf(uuid.get("uuid").toString());
                }
                if(uuid2!=null &&(!uuid2.get("uuid").toString().equals(""))) {
                    number2 = Integer.valueOf(uuid2.get("uuid").toString());
                }
                HoMap.put("by", ContextUtils.getUserId());//操作人
                HoMap.put("Recorder",ContextUtils.getUserId());// 水表记录人编号
                HoMap.put("IfGenerate",1);//是否生成账单  0.未生成  1.已生成',
                HoMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                HoMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(HoMap);
                HoMap.put("GenerateTime",HoMap.get("instm"));//账单生成日期
                HoMap.put("StaTime",HoMap.get("GenerateTime"));//账单周期--开始时间
                HoMap.put("EndTime",ConvertDateTime.dateFormatTimeToStr(ConvertDateTime.FORMAT_ONLY_DATE_EN,ConvertDateTime.addDateTime(ConvertDateTime.getCurDate(),15,4)));//账单周期--结束时间
                List<Map<String,Object>> listMap=(List<Map<String,Object>>)params.get("data");
                System.out.println("listMAp:"+listMap);
                Calendar now = Calendar.getInstance();
                int month= (now.get(Calendar.MONTH) + 1);
                int num=0;
                for (Map<String,Object> dataMap:listMap){
                    List<Map<String,Object>> billList=(List<Map<String,Object>>)dataMap.get("billData");
                    UUID= ComUtils.getLocalTrmSeqNum("wm"+num,number);//水表抄表记录编号
                    UUID3=ComUtils.getLocalTrmSeqNum("ba"+num,number);
                    dataMap.putAll(HoMap);
                    System.out.println("水表新增的记录:"+dataMap);
                    dataMap.put("WameId",UUID);
                    dataMap.put("BatchId",UUID3);
                    hoWaterMeterMapper.addHoWaterMeter(dataMap);
                    for (int i=0;i<billList.size();i++){
                        UUID2=ComUtils.getLocalTrmSeqNum("zdzc"+num,number2);//账单编号
                        Map<String,Object>billMap=billList.get(i);
                        //收入账单
                        billMap.put("instm",HoMap.get("instm"));
                        billMap.put("insterm",HoMap.get("insterm"));
                        billMap.put("insby",HoMap.get("insby"));
                        billMap.put("insfnc",HoMap.get("insfnc"));
                        billMap.put("BiGenerated",HoMap.get("instm"));//账单生成日期
                        billMap.put("BiId",UUID2);
                        billMap.put("BiName",month+"月份水费账单");
                        billMap.put("BiType","2");//账单类型  1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                        billMap.put("LateDay",HoMap.get("EndTime"));//最晚付款时间
                        billMap.put("EndTime",billMap.get("LateDay"));//账单结束时间 计算十五天之后的时间、
                        billMap.put("BiName",month+"月份水费账单");
                        billMap.put("Source",UUID);//来源编号
                        billMap.put("BillExplain","水费:"+billMap.get("BiMoney"));
                        billMap.put("BiType",2);// 1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                        billMap.put("PubType",1);//1.水费  2.电费  3.燃气',
                        billMap.put("IfAdjust",0);//当前账单是否可以调整   0.否  1.是,
                        billMap.put("CreateType","2");//房源详表
                        billMap.put("Create",ContextUtils.getUserId());//账单创建人
                        if (billMap.get("TenId")!=null && !billMap.get("TenId").toString().equals("")){
                            seTenantBillMapper.addTenantBill(billMap);
                            num++;
                        }
                    }
                }
                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 服务管家退租的时候查询上个月的水表抄表记录
     */
    public Map<String,Object> getHoWaterMeterLast(Map<String,Object> params){
        Map<String,Object> map=hoWaterMeterMapper.getHoWaterMeterLast(params);
        if (map==null){
            map=new HashMap<String,Object>();
        }
        return map;
    }
    /**
     * 根据水表抄表编号查询一个批次录入的一套房源的表数
     */
    @Override
    public JsonResult getHoWaterMeterBatc(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        if (params.get("WameId")==null){
            return  result.putFailed("参数不正确");
        }
        Map<String,Object> map=hoWaterMeterMapper.getHoWaterMeterBatc(params);
        params.put("Source",params.get("WameId"));//账单的来源编号
        if (map!=null){
            //查询水表抄表记录关联的账单信息
            List<Map<String,Object>> list=hoTenantBillMapper.getHoBillList(params);
            if (list!=null){
                map.put("list",list);
                result.put(map);
            }else{
                result.putFailed("服务器繁忙");
            }
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
    /**
     * 租后主管撤回水气表账单(账单错误)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult recallHoWaterMeter(Map<String, Object> params) {

        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("WaterData")==null){//燃气抄表记录及抄表记录对应的账单
                    return result.putFailed("参数不正确");
                }
                Map<String,Object> WaterData=(Map<String,Object>)params.get("WaterData");
                //水气抄表记录关联账单记录
                List<Map<String,Object>> GasBillList=(List<Map<String,Object>>)WaterData.get("list");
                //组装修改参数
                Map<String,Object> updateMap=new HashMap<String,Object>();
                updateMap.put("by", ContextUtils.getUserId());//操作人
                updateMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                updateMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(updateMap);
                Map<String,Object> insterMap=new HashMap<String,Object>();
                insterMap.put("by", ContextUtils.getUserId());//操作人
                insterMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                insterMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(insterMap);
                updateMap.put("delfg", "1");//0正常 1废弃
                updateMap.put("WameId",WaterData.get("WameId"));//水表抄表记录
                hoWaterMeterMapper.updateHoWaterDelfg(updateMap);//撤回抄表记录
                updateMap.put("Source",WaterData.get("WameId"));//账单来源编号
                updateMap.put("Status","4");//账单状态   1.待支付  2.支付完成  3待审核   4.账单废弃（租客违约）5审核驳回
                seTenantBillMapper.updateSeWaterGasDelfg(updateMap);//撤回账单

                //新增抄表记录和收入账单
                WaterData.putAll(insterMap);
                System.out.println("WaterData:"+WaterData);
                hoWaterMeterMapper.addHoWaterMeter(WaterData);//新增水表抄表记录
                for (Map<String,Object> map: GasBillList){
                    map.putAll(insterMap);
                    seTenantBillMapper.addTenantBill(map);//新增账单
                }
                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 租后主管撤回电表账单(审核错误)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult examHoWaterMeter(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("WaterData")==null){//账单信息及账单支付信息
                    return result.putFailed("参数不正确");
                }
                //需要撤回的账单集合
                Map<String,Object> WaterData=(Map<String,Object>)params.get("WaterData");
                //组装修改参数
                Map<String,Object> updateMap=new HashMap<String,Object>();
                updateMap.put("by", ContextUtils.getUserId());//操作人
                updateMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                updateMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(updateMap);
                Map<String,Object> insterMap=new HashMap<String,Object>();
                insterMap.put("by", ContextUtils.getUserId());//操作人
                insterMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                insterMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(insterMap);
                updateMap.putAll(WaterData);
                updateMap.put("delfg","1");//0正常 1废弃
                seTenantBillMapper.updateSeTenantDelfg(updateMap);//撤回账单
                seBillPayMapper.updateSeBillDelfg(updateMap);//撤回支付信息
                insterMap.putAll(WaterData);
                seTenantBillMapper.addTenantBill(insterMap);//新增账单
                if (insterMap.get("IfOperaType").toString().equals(0)) {//是否是整租 0否 1是 2（秘书抄表）
                    seBillPayMapper.addSeBillPay(insterMap);//新增支出账单信息
                }
                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 查询上一次水费
     * @param params
     * @return
     */
    @Override
    public JsonResult getHouInfoMater(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        return result.put(hoWaterMeterMapper.getHouInfoMater(params));
    }
}
